import 'dart:convert';

import 'package:aero_frisbee/app/model/af_create_post_param_model/af_create_post_param_model.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'af_create_post_view_model.g.dart';

@riverpod
class AfCreatePostService extends _$AfCreatePostService {
  @override
  AfCreatePostParamModel build() {
    return AfCreatePostParamModel();
  }

  updateTitle(String title) {
    state = state.copyWith(title: title);
  }

  updateContent(String content) {
    state = state.copyWith(content: content);
  }

  addImgUrl(String imgUrl) {
    state = state.copyWith(imgs: [...state.imgs, imgUrl]);
  }

  removeImgUrl(String imgUrl) {
    state = state.copyWith(imgs: state.imgs.where((e) => e != imgUrl).toList());
  }
}

@Riverpod(keepAlive: true)
class AfMyCreatedPostsListService extends _$AfMyCreatedPostsListService {
  @override
  List<AfCreatePostParamModel> build() {
    final userId = ref.watch(curlUserInfoProvider)?.userInfoModel?.userId;
    if (userId != null) {
      final prefs = ref.read(appPrefsProvider);
      final bindListStr = prefs.getString('create.post.list.key_$userId');
      if (bindListStr != null && bindListStr.isNotEmpty) {
        final bindList = List<AfCreatePostParamModel>.from(
            jsonDecode(bindListStr)
                .map((x) => AfCreatePostParamModel.fromJson(x)));
        return bindList;
      }
    }
    return [];
  }

  creatPost(AfCreatePostParamModel post) async {
    final userInfo = ref.read(curlUserInfoProvider)?.userInfoModel;
    state = [...state, post.copyWith(userInfo: userInfo)];
    if (userInfo?.userId != null) {
      final prefs = ref.read(appPrefsProvider);
      await prefs.setString(
          'create.post.list.key_${userInfo!.userId}', jsonEncode(state));
    }
  }

  deletePost(AfCreatePostParamModel post) {
    state = state.where((element) => element != post).toList();
    final userInfo = ref.read(curlUserInfoProvider)?.userInfoModel;
    if (userInfo?.userId != null) {
      final prefs = ref.read(appPrefsProvider);
      prefs.setString(
          'create.post.list.key_${userInfo!.userId}', jsonEncode(state));
    }
  }

  toggleLike(AfCreatePostParamModel post) {
    state = state
        .map((e) => e == post ? post.copyWith(isLike: !post.isLike) : e)
        .toList();
    final userInfo = ref.read(curlUserInfoProvider)?.userInfoModel;
    if (userInfo?.userId != null) {
      final prefs = ref.read(appPrefsProvider);
      prefs.setString(
          'create.post.list.key_${userInfo!.userId}', jsonEncode(state));
    }
  }
}
